import {getUserInfo} from '../../api/member.js';
import {getTaskDetail, addTaskContent} from "../../api/activity";

import Util from '../../utils/util.js';

const app = getApp();
Page({
  data: {
    batActive: true,
    fields: {
      content: {
        title: "随想",
        type: "textarea"
      },
      picture_ids: {
        title: "",
        type: "pictures"
      }
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const that = this;

    Util.chekWxLogin().then(res => {
      getUserInfo().then(result => {
        that.setData({
          member: result.data || {}
        })
        if (Util.isEmpty(result.data.avatar)) {
          wx.navigateTo({
            url: "../member/edit"
          });
          return;
        }
      }).catch(errmsg => {
        app.Tips({title: errmsg})
      })
    })

    this.onLoadTabbar();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  formSubmit(e) {
    const that = this,
      fields = that.data.fields,
      form_data = e.detail.value;

    if (!this.data.batActive)
      return false;

    let msg = "";
    for (const k in fields) {
      if (fields[k].type == "file") continue;

      if (fields[k].type == 'pictures') {
        let picture_ids = [];

        for (const j in fields[k].values) {
          picture_ids.push(fields[k].values[j].picture_id);
        }

        if (picture_ids.length < 1) {
          msg = fields[k].title + "必填";
          break;
        }

        form_data[k] = picture_ids
        continue;
      }

      if (!form_data[k]) {
        msg = fields[k].title + "必填";
        break;
      }
    }

    if (msg) {
      return app.Tips({title: msg});
    }

    form_data['type'] = 3;
    that.setData({
      batActive: false
    })

    wx.showLoading({title: "正在提交..."})
    addTaskContent(form_data).then(res => {
      wx.setStorageSync('is_refresh', 1)
      that.setData({
        batActive: true
      })
      return app.Tips({
        title: "提交成功",
        icon: "success"
      }, {
        tab: 5,
        url: "result?type=3"
      })
    }).catch(errmsg => {
      that.setData({batActive: true})
      return app.Tips({title: errmsg}, {tab: 3})
    })
  },

  inputName(e) {
    let fields = this.data.fields;
    const id = e.currentTarget.id;
    fields[id].default_val = e.detail.value;
    this.setData({fields: fields});
  },

  onChooseMutiImage(e) {
    const that = this,
      key = e.currentTarget.dataset.key;

    let fields = that.data.fields,
      images = fields[key].values || [];
    let size = 6 - images.length

    wx.chooseImage({
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      count: size,
      success: function (res) {
        const tempFilePaths = res.tempFilePaths;

        wx.showLoading({
          title: '正在上传',
          mask: true,
        })
        const url = `${app.globalData.url}/api/upload`; // 仅为示例，非真实的接口地址
        for (let index = 0; index < tempFilePaths.length; index++) {
          // images.push({ path_preview: tempFilePaths[index],path: tempFilePaths[index]  });
          wx.uploadFile({
            url: url,
            filePath: tempFilePaths[index],
            name: 'fileData',
            header: {
              token: wx.getStorageSync("cookie_token")
            },
            formData: {},
            success(res) {
              const data = JSON.parse(res.data);
              images.push({
                path: data.path,
                picture_id: data.id
              });

              fields[key].values = images

              that.setData({fields: fields})
              if (index + 1 == tempFilePaths.length) {
                wx.hideLoading();
              }
            }
          });
        }
      }
    });
  },

  uploadTaskFile(e) {
    const _this = this,
      fields = _this.data.fields,
      key = e.currentTarget.dataset.key,
      fileIds = fields[key].file_ids || [],
      files = fields[key].files || [];

    console.log(files, fields)
    return
    const header = {
      'content-type': 'multipart/form-data',
      cookie: wx.getStorageSync('JSESSIONID')
    };
    wx.chooseMessageFile({
      count: 1,
      type: 'all',
      success(res) {
        const tempFilePaths = res.tempFiles;
        let canUpload = true;

      }
    })
  },

  removePic(e) {
    const that = this,
      fk = e.currentTarget.dataset.fk,
      index = e.currentTarget.dataset.k

    let fields = that.data.fields
    if (fields[fk].values[index].id) {
      deletePicture(fields[fk].values[index].picture_id)
        .then(res => {
          fields[fk].values.splice(index, 1)
          that.setData({fields: fields})
        })
        .catch(errmsg => {
          app.Tips({title: errmsg})
        })
    } else {
      fields[fk].values.splice(index, 1)
      that.setData({fields: fields})
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },
  onLoadTabbar: function () {//底部tabbar返回数据
    const that = this;

    Util.checkIphone().then(res => {//检查是否是iphone x/11等
      that.setData({
        isIphoneX: res
      })
    });

    wx.createSelectorQuery().in(that).select('#weui-footer')
      .boundingClientRect(function (rect) {
        that.setData({
          bottom: parseInt(rect.height) + 15
        })
      }).exec()
  },


  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }

})